import {Component, OnInit} from '@angular/core';
import * as moment from "moment";
import {FetchService} from "../../../../core/net/fetch.service";
import {differenceInCalendarDays} from 'date-fns';
import * as _ from "lodash";


const CropPropsHash = {
    'wheat': '小麦',
    'rice': '水稻',
    'corn': '玉米',
    'otherTotal': '其他作物'
};

@Component({
    selector: 'app-agri-crop',
    templateUrl: './agri-crop.component.html',
    styleUrls: ['./agri-crop.component.scss', '../agriculture.component.scss']
})
export class AgriCropComponent implements OnInit {
    listData = [];
    year = moment().valueOf();
    stadiaCode: string; //  当前测站编码
    stationName: string;
    tableData = [];
    baseOpt: any = {
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "shadow"
            }
        },
        legend: {
            data: [],
            bottom: 0
        },
        grid: {
            top: "10%",
            bottom: "8%",
            left: "6%",
            right: "4%",
            containLabel: true
        },
        xAxis: {
            type: "category",
            data: []
        },
        yAxis: {
            type: "value"
        },
        series: []
    };
    irrOptChange: any = {};
    echartsIntance: any;
    tableHead = [];

    /******************* end *******************/
    constructor(private fetchService: FetchService) {
    }

    ngOnInit() {
        this.fetchService.get<any>('report/muwIrr/listAllSite', {}).subscribe(res => {
            console.log(res);
            this.listData = res;
            this.selectedAreaChanged(this.listData[0].id);
        });
    }

    disabledDate = (current: Date): boolean => {
        // 不能选今年之后的日期
        return differenceInCalendarDays(current, moment().valueOf()) > 0;
    }

    chartInit(ec) {
        this.echartsIntance = ec;
    }

    selectedAreaChanged(id): void {
        const selectedArea = _.find(this.listData, item => {
            return item.id === id;
        });
        this.stationName = selectedArea.name;
        this.stadiaCode = id;
        this.queryInfo();
    }

    queryInfo(): void {
        this.tableData = [];
        this.tableHead = [];
        this.irrOptChange = {
            legend: {
                data: []
            },
            yAxis: {
                type: "value"
            },
            xAxis: {
                type: "category",
                data: []
            },
            series: []
        };
        this.fetchService.post<any>('report/muwIrr/data', {
            id: this.stadiaCode,
            year: moment(this.year).year()
        }).subscribe(res => {
            console.log(res);
            if (res && res.data.length && res.data[0]) {
                const legendData = [];
                const propsData = [];
                res.data.forEach(item => {
                    item['irrTotal'] = parseFloat(item['wheat'] || '0') +
                        parseFloat(item['corn'] || '0') +
                        parseFloat(item['rice'] || '0') +
                        parseFloat(item['otherTotal'] || '0');
                });
                if (res.type === 1) {
                    //  夏秋灌
                    Object.keys(res.data[0]).forEach(prop => {
                        if (CropPropsHash[prop]) {
                            legendData.push(CropPropsHash[prop]);
                            propsData.push(prop);
                        }
                    });
                } else if (res.type === 2) {
                    //  冬灌
                    legendData.push('灌溉面积');
                    propsData.push('irrTotal');
                }
                this.tableHead = res.data.map(item => {
                    return item.areaName;
                });
                this.irrOptChange = {
                    legend: {
                        data: legendData
                    },
                    xAxis: {
                        data: this.tableHead
                    },
                    series: legendData.map((o, idx) => {
                        return {
                            name: o,
                            type: "bar",
                            data: res.data.map(item => {
                                return item[propsData[idx]];
                            })
                        };
                    })
                };
                this.tableData = legendData.map((crop, idx) => {
                    const result = {
                        cropName: crop,
                        irrTotal: this.getItemValues(res.data, propsData[idx]).reduce((def, val) => {
                            def += parseFloat(val || '0');
                            return def;
                        }, 0)
                    };
                    this.tableHead.forEach(areaName => {
                        result[areaName] = _.find(res.data, obj => {
                            return obj.areaName === areaName;
                        })[propsData[idx]];
                    });
                    return result;
                });
            }
            // this.echartsIntance.setOption(this.irrOptChange, true);
        });
    }

    private getItemValues(list, key) {
        return list.map(i => {
            return i[key] || 0;
        });
    }
}
